package com.cloud.easy.im.utils;

import com.cloud.easy.im.argeement.Agreement;
import com.cloud.easy.im.event.ServerEventListener;
import com.cloud.easy.im.handler.qos.QoS4RecivedDaemonC2S;
import com.cloud.easy.im.netty.IMObserver;
import com.cloud.easy.im.processor.OnlineProcessor;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

/**
 * 全局消息发送
 *
 * @author wangjian
 * @version 0.1.0
 * @create 2020年09月16日11:31 上午
 */
public class GlobalSendHelper {

    private static final Logger logger = LoggerFactory.getLogger(GlobalSendHelper.class);

    /**
     * 客户端 --> 客户端
     *
     * @param session             发送者channel
     * @param agreement           发送者data
     * @param serverEventListener 事件监听回调
     */
    public static void sendDataC2C(Channel session, Agreement agreement, ServerEventListener serverEventListener) throws InterruptedException {
        //消息发送前置操作
        serverEventListener.messageBefore_CallBack(agreement);
        //判断是否需要发送ack应答包 87ue
        if (agreement.isQoS()) {
            // 将发送者需要qos机制的fp存入
            if (QoS4RecivedDaemonC2S.getInstance().addRecieved(agreement)) {
                IMObserver resultObserver = new IMObserver() {
                    @Override
                    public void update(boolean receivedBackSendSucess, Object extraObj) {
                        if (receivedBackSendSucess) {
                            logger.debug("[GLOBAL_SEND_HELPER]【QoS_伪应答_C2S】向" + agreement.getFrom() + "发送" + agreement.getFp()
                                    + "的伪应答包成功,伪装from自：" + agreement.getTo() + "产品:" + agreement.getProductCode());
                        }
                    }
                };
                //发送伪应答包
                LocalSendHelper.replyDelegateRecievedBack(session, agreement, resultObserver);
            } else {
                logger.error("[GLOBAL_SEND_HELPER]发送者" + agreement.getFrom() + "发送" + agreement.getFp() + "带有qos机制的消息，但是添加队列失败！" +
                        "可能是消息体结构错误，agreement：" + agreement.toJsonString());
            }
        }
        //设置回调
        IMObserver resultObserver = new IMObserver() {
            @Override
            public void update(boolean sucess, Object extraObj) {
                if (sucess) {
                    //发送成功,聊天信息收集
                    serverEventListener.messageSendSuccess_C2C_CallBack(agreement);
                } else {
                    //发送失败
                    logger.info("[GLOBAL_SEND_HELPER<sendDataC2C>]>> 客户端[" + agreement.getFrom() + "|" + agreement.getProductCode() + "]的通用数据尝试实时发送没有成功，将交给应用层进行离线存储哦...");
                    //发送失败，回调做离线处理
                    boolean callBack = serverEventListener.messageSendFaild_C2C_CallBack(agreement);
                    if (!callBack) {
                        logger.warn("[GLOBAL_SEND_HELPER<sendDataC2C>]>> 客户端[" + agreement.getFrom() + "|" + agreement.getProductCode() + "]的通用数据传输消息尝试实时发送没有成功，将交给应用层" +
                                "进行离线存储依然失败...，此消息将被服务端丢弃！");
                    }
                }
            }
        };

        LocalSendHelper.sendData(agreement, resultObserver);
    }

    /**
     * 客户端 --> 客户端 群聊
     *
     * @param dataFromClient      发送者data
     * @param serverEventListener 事件监听回调
     */
    public static void sendGroupDataC2C(Agreement dataFromClient, ServerEventListener serverEventListener) throws InterruptedException {
        if (dataFromClient != null) {
            //回调接口返回当前群组人员id
            List<String> userIds = serverEventListener.messageGroupAction_CallBack(dataFromClient.getTo(), dataFromClient.getFrom());

            //消息发送前置操作
            serverEventListener.messageBefore_CallBack(dataFromClient);

            IMObserver resultObserver = new IMObserver() {
                @Override
                public void update(boolean sucess, Object extraObj) {
                    if (sucess) {
                        //发送成功,聊天信息收集
                        serverEventListener.messageSendSuccess_C2C_CallBack(dataFromClient);
                    } else {
                        //发送失败
                        logger.info("[GLOBAL_SEND_HELPER<sendGroupDataC2C>]>> 客户端[" + dataFromClient.getFrom() + "|" + dataFromClient.getProductCode() + "]的通用数据尝试实时发送没有成功，将交给应用层进行离线存储哦...");
                        //发送失败，回调做离线处理
                        boolean callBack = serverEventListener.messageSendFaild_C2C_CallBack(dataFromClient);
                        if (!callBack) {
                            logger.warn("[GLOBAL_SEND_HELPER<sendGroupDataC2C>]>> 客户端[" + dataFromClient.getFrom() + "|" + dataFromClient.getProductCode() + "]的通用数据传输消息尝试实时发送没有成功，将交给应用层" +
                                    "进行离线存储依然失败...，此消息将被服务端丢弃！");
                        }
                    }
                }
            };

            for (String toUserId : userIds) {
                LocalSendHelper.sendData(OnlineProcessor.getInstance().getOnlineSession(toUserId, dataFromClient.getProductCode()), dataFromClient, resultObserver);
            }

        }
    }
}
